﻿Imports System.Data

Partial Class Content_Administracion_Adm_controls_Usuarios
    Inherits System.Web.UI.UserControl


    Dim IDataBase As New Clases.DataBase
    Dim ECConnString As String = ConfigurationManager.AppSettings("dbIP")
    Dim IControles As New Clases.controles

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim q1, q2 As String
            'q1 = "select * from TEstatus where stat_id in (1,2)"
            'IControles.fill_dropDownListBaseQuery(ddl_status, "TEstatus", "stat_id", "stat_nombre", q1)
            'IControles.fill_dropDownListBaseQuery(ddl_searchStatus, "TEstatus", "stat_id", "stat_nombre", q1)
            'IControles.addNoneAllElement(ddl_searchStatus)

            q2 = "select * from Troles where stat_id=1"
            IControles.fill_dropDownListBaseQuery(ddl_rol, "TRoles", "rol_id", "rol_nombre", q2)
            IControles.fill_dropDownListBaseQuery(ddl_searchrol, "TRoles", "rol_id", "rol_nombre", q2)
            IControles.addNoneAllElement(ddl_searchrol)

            IControles.addNoneAllElement(ddl_rol)
            'IControles.addNoneAllElement(ddl_status)

        End If
    End Sub

    'Funcion que inserta en la base de datos los valores

    Protected Sub btn_insertUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_insertUser.Click
        Dim insertUser, dmluser(), valUser, qryValidaUser, resultTransaction As String

        qryValidaUser = "Select Count(*) As Usuario  from TUsuarios where usr_usuarios='" & txt_userLogin.Text & "'"
        valUser = IDataBase.getSimpleData(qryValidaUser, "Usuario")

        If valUser <= 0 Then

            If txt_pass.Text = txt_pass2.Text Then
                insertUser = "insert into TUsuarios (usr_nombre,usr_usuarios,usr_contrasena,usr_email,rol_id,stat_id,usr_titular,usr_fecha_registro) values ('" & txt_nombre.Text & "','" & txt_userLogin.Text & "','" & txt_pass2.Text & "','" & txt_email.Text & "'," & ddl_rol.SelectedValue & ",1,'" & Session("ActiveUserlogin") & "',default)"
                IDataBase.addStringToArray(dmluser, insertUser)

            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Las contraseñas no concuerdan');", True)
                Exit Sub

            End If

            resultTransaction = IDataBase.execute_commandsArray(dmluser, lb_error)
            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Usuario Registrado Exitosamente')", True)
                IControles.fillGridViewPaging(gv_users, "Select Distinct Usr_Id,   usr_usuarios, Usr_nombre, Usr_Email, rol_nombre,stat_nombre" & _
                         " From dbo.vwUsuarios Where 1=1")
                clearFieldData()
            Else

                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            End If

        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El usuario ya existe');", True)
        End If

    End Sub

    Protected Sub btn_searchUser_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_searchUser.Click
        'se extraen los datos de la consulta configurada
        Dim qrySearchUsers As String


        'qrySearchUsers = "Select Distinct Usr_Id,   usr_usuarios, Usr_nombre, Usr_Email, rol_nombre,stat_nombre From dbo.vwUsuarios Where 1=1"
        qrySearchUsers = "Select Distinct * From dbo.vwUsuarios Where 1=1"


        If txt_searchDisplayName.Text <> "" Then
            qrySearchUsers = qrySearchUsers & " and Usr_nombre like '%" & txt_searchDisplayName.Text & "%'"
        End If
        If txt_searchEMail.Text <> "" Then
            qrySearchUsers = qrySearchUsers & " and usr_email like '%" & txt_searchEMail.Text & "%'"
        End If
        If txt_searchLogin.Text <> "" Then
            qrySearchUsers = qrySearchUsers & " and usr_usuarios like '%" & txt_searchLogin.Text & "%'"
        End If


        'If ddl_searchStatus.SelectedValue <> "None" Then
        '    qrySearchUsers = qrySearchUsers & " and stat_nombre = '" & ddl_searchStatus.SelectedItem.ToString & "' "
        'End If

        If ddl_searchrol.SelectedValue <> "None" Then
            qrySearchUsers = qrySearchUsers & " and rol_nombre = '" & ddl_searchrol.SelectedItem.ToString & "' "
        End If

        qrySearchUsers = qrySearchUsers & " order by usr_nombre "
        hf_qryBusqueda.Value = qrySearchUsers
        hf_Usuarios.Value = qrySearchUsers
        IControles.fillGridViewPaging(gv_users, hf_qryBusqueda.Value)
    End Sub

    Protected Sub gv_users_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv_users.PageIndexChanging
        'se genera la paginación del gridview
        IControles.fillGridViewPaging(gv_users, hf_qryBusqueda.Value, Convert.ToInt32(e.NewPageIndex))
    End Sub

    Protected Sub gv_users_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_users.RowCommand
        If e.CommandName = "editarUsuario" Then
            clearFieldData()
            loadUserData(e.CommandArgument)
        ElseIf e.CommandName = "eliminaUsuario" Then
            eliUsuario(e.CommandArgument)
        End If
    End Sub

    Protected Sub eliUsuario(ByVal id As Integer)
        Dim array(), query2, resultTransaction As String
        Dim valor, q, q1, valor1, qu, valor2, algo, otro, otro1 As String

        algo = Session("ActiveUserlogin")

        qu = "Select rol_id from TUsuarios where usr_id = " & id
        valor2 = IDataBase.getSimpleData(qu, "rol_id")
        If valor2 = "1" Then
            otro = "Select COUNT(*) as cantidad from vwUsuarios where rol_id = 1 "
            otro1 = IDataBase.getSimpleData(otro, "cantidad")
            If otro1 < "0" Or otro1 = "1" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error no puedes eliminar al ultimo administrador');", True)
            End If

        ElseIf valor2 = "2" Then
            q = "select COUNT(*) as cantidad from vwClientes where usrAse_id = " & id
            valor = IDataBase.getSimpleData(q, "cantidad")
        ElseIf valor2 = "3" Then
            q = "select COUNT(*) as cantidad from vwClientes where usrProm_id = " & id
            valor = IDataBase.getSimpleData(q, "cantidad")
        End If

        q1 = "Select usr_usuarios from vwUsuarios where usr_id = " & id
        valor1 = IDataBase.getSimpleData(q1, "usr_usuarios")
        'el primer if es solo para los administradores
        'el segundo es para un promotor o asesor si su valor es 0
        'el tercero es para un promotor o asesor si su valor es diferente de 0
        'el else es si ninguna de las 2 o una de las condiciones no se cumplieron del primer else
        If algo = valor1 And otro1 > "1" Then
            'If otro1 > "1" Then
            query2 = "delete from TUsuarios  where usr_id = " & id
            IDataBase.addStringToArray(array, query2)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)
            'Else
            '   ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El usuario no puede ser eliminado porque existe al menos un cliente que lo tiene registrado');", True)
            'End If
            'ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Redirigiendo....');", True)
            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Usuario Eliminado Exitosamente');window.location.href=' /public_html/Equipo1/Login.aspx'", True)
            End If
            ' como redirigir al usaurio 
            'Response.Redirect("Login.aspx")
            'FormsAuthentication.RedirectFromLoginPage(Session("ActiveUserDisplayName"), False)
            'FormsAuthentication.RedirectToLoginPage()
            'Server.Transfer("Login.aspx", True)
        ElseIf algo <> valor1 And otro1 > "1" Then
            query2 = "delete from TUsuarios  where usr_id = " & id
            IDataBase.addStringToArray(array, query2)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)
        ElseIf valor = "0" Then

            query2 = "delete from TUsuarios  where usr_id = " & id
            IDataBase.addStringToArray(array, query2)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)

        ElseIf valor <> "0" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El usuario no puede ser eliminado porque existe al menos un cliente que lo tiene registrado');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El usuario no puede ser eliminado porque es el ultimo administrador');", True)
        End If

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Usuario eliminado Exitosamente');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If

        IControles.fillGridViewPaging(gv_users, "select * from vwUsuarios order by usr_nombre")
    End Sub

    Protected Sub clearFieldData()
        txt_userLogin.Text = ""
        txt_email.Text = ""
        txt_nombre.Text = ""
        lb_username.Text = ""
        txt_pass.Text = ""
        txt_pass2.Text = ""
        txt_pass3.Text = ""
        txt_pass4.Text = ""
        btn_insertUser.Visible = True
        btn_updateUser.Visible = False
        txt_pass.Visible = True
        txt_pass2.Visible = True
        txt_pass3.Visible = False
        txt_pass4.Visible = False
        lb_username.Visible = False
        txt_userLogin.Visible = True
        lb_username.Visible = False
        ddl_rol.SelectedIndex = 0
        'ddl_status.SelectedIndex = 0
    End Sub

    Protected Sub loadUserData(ByVal user_ID As Integer)
        btn_updateUser.Visible = True
        btn_insertUser.Visible = False
        txt_userLogin.Visible = False
        lb_username.Visible = True
        txt_pass3.Visible = True
        txt_pass4.Visible = True
        txt_pass.Visible = False
        txt_pass2.Visible = False

        Dim datosUsuario As New DataTable

        Dim dmlGetUserData As String

        dmlGetUserData = "select Distinct Top 1 * from vwUsuarios where usr_id = '" & user_ID & "' "
        IDataBase.createDataTable(datosUsuario, dmlGetUserData)
        If datosUsuario IsNot Nothing Then
            txt_nombre.Text = datosUsuario.Rows(0)("usr_nombre")
            lb_username.Text = datosUsuario.Rows(0)("usr_usuarios")
            txt_pass3.Text = datosUsuario.Rows(0)("usr_contrasena")
            txt_pass4.Text = txt_pass3.Text
            txt_email.Text = datosUsuario.Rows(0)("usr_email")
            ddl_rol.SelectedValue = datosUsuario.Rows(0)("rol_id")
            'ddl_status.SelectedValue = datosUsuario.Rows(0)("stat_id")
        End If
        Session("usr_id") = user_ID
    End Sub

    Protected Sub btn_updateUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_updateUser.Click
        Dim dmlUpdateUser() As String
        Dim UpdateUser As String
        Dim resultTransaction As String

        UpdateUser = "Update TUsuarios set usr_nombre='" & txt_nombre.Text & "',usr_contrasena='" & txt_pass3.Text & "',usr_email='" & txt_email.Text & "',rol_id='" & ddl_rol.SelectedValue & "',stat_id='1' where usr_id='" & Session("usr_id") & "' "
        IDataBase.addStringToArray(dmlUpdateUser, UpdateUser)

        resultTransaction = IDataBase.execute_commandsArray(dmlUpdateUser, lb_error)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Usuario Modificado Exitosamente');window.location.href='Usuarios.aspx'", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
    End Sub

    Protected Sub btn_cancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
        clearFieldData()
    End Sub

    Protected Sub gv_users_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv_users.PageIndexChanging        
        IControles.fillGridViewPaging(gv_users, hf_Usuarios.Value, Convert.ToInt32(e.NewPageIndex))        
    End Sub
End Class